/**
 * @(#)com.framework.web.wechat.controller.WeChatCookbookController
 *
 * Copyright (c) 2014-2018 一抹风光
 *
 * DESC:
 *
 */
package com.framework.web.wechat.controller;

import com.framework.core.domain.SessionVo;
import com.framework.core.util.DateUtils;
import com.framework.core.util.Persistence;
import com.framework.core.util.StringUtil;
import com.framework.web.bus.domain.Cookbook;
import com.framework.web.bus.domain.CookingSteps;
import com.framework.web.bus.domain.Ingredients;
import com.framework.web.bus.domain.Thumb;
import com.framework.web.bus.service.CookbookService;
import com.framework.web.bus.service.CookingStepsService;
import com.framework.web.bus.service.IngredientsService;
import com.framework.web.bus.service.ThumbService;
import com.framework.web.common.domain.BusinessConstants;
import com.framework.web.common.domain.Constants;
import com.framework.web.wechat.domain.WeChatRequest;
import com.framework.web.wechat.domain.WeChatResInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author fusf
 * @version 1.0  2016/9/11
 */
@Controller
@RequestMapping("/weChat/cookbook")
public class WeChatCookbookController {

    @Autowired
    private CookbookService cookbookService;

    @Autowired
    private IngredientsService ingredientsService;

    @Autowired
    private CookingStepsService cookingStepsService;

    @Autowired
    private ThumbService thumbService;


    /**
     * 菜谱列表列表
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getCookList", method = RequestMethod.GET)
    @ResponseBody
    public Object getCookbookList(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        Map<String, Object> map = new HashMap<>();
        PageRequest pr = new PageRequest(requestInfo.getPage() - 1, requestInfo.getCount());
        Page<Cookbook> cookbookPage = cookbookService.getPageList(new Cookbook(), pr);
        List<Cookbook> cookbookList = cookbookPage.getContent();
        List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
        String userId = "";
        if (StringUtil.isNotEmpty(requestInfo.getUserGuid())) {
            ServletContext application = request.getSession().getServletContext();
            if (application.getAttribute(requestInfo.getUserGuid()) != null) {
                SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
                if (sessionVo != null) {
                    userId = sessionVo.getUserId();
                }
            }
        }
        for (Cookbook cookbook : cookbookList) {
            Map<String, Object> map_object = new HashMap<>();
            map_object.put("repiceId", cookbook.getId());//ID
            map_object.put("image", Persistence.getValue(Constants.FILEIP) + cookbook.getImg());//图片 TODO
            map_object.put("review", cookbook.getComments());//点评
            map_object.put("time", DateUtils.formateDate(cookbook.getCreateTime()));//创建时间 TODO
            map_object.put("author", cookbook.getAuthor());//作者
            map_object.put("thumb", cookbook.getPraiseCount());//点赞数
            map_object.put("repiceName", cookbook.getCookbookName());//菜谱名称
            Integer isThumb = BusinessConstants.CLICK_LIKE.NO;
            if (StringUtil.isNotEmpty(userId)) {//判断是否点赞
                Thumb thumb = thumbService.findByUserIdAndCookbookId(userId, cookbook.getId());
                if (thumb != null) {
                    if (BusinessConstants.THUMBSTATE.INVALID == thumb.getStatus()) {
                        isThumb = BusinessConstants.CLICK_LIKE.YES;
                    }
                }
            }
            map_object.put("isThumb", isThumb);//是否已经点赞
            mapList.add(map_object);
        }
        map.put("infoList", mapList);
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;

    }

    /**
     * 菜谱详情
     *
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/bookDetail", method = RequestMethod.GET)
    @ResponseBody
    public Object getCookbookDetail(String repiceId, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        Map<String, Object> map = new HashMap<>();
        Cookbook cookbook = cookbookService.findById(repiceId);
        map.put("repiceId", cookbook.getId());//ID
        map.put("image", Persistence.getValue(Constants.FILEIP) + cookbook.getImg());//图片 TODO
        map.put("review", cookbook.getComments());//点评
        map.put("time", DateUtils.formateDate(cookbook.getCreateTime()));//创建时间 TODO
        map.put("author", cookbook.getAuthor());//作者
        map.put("thumbNumber", cookbook.getPraiseCount());//点赞数
        map.put("readNumber", cookbook.getPraiseCount());//阅读数
        map.put("commentNumber", cookbook.getPraiseCount());//评论数
        map.put("experince", cookbook.getExperience());//美味体验
        map.put("healthTip", cookbook.getHealth()); //养生必读
        //map.put("repiceName", cookbook.getCookbookName());//菜谱名称
        //根据菜谱Id,获取食材列表
        List<Ingredients> ingredientsList = ingredientsService.findByCookbookId(repiceId);
        List<Map<String, Object>> mapList_materials = new ArrayList<Map<String, Object>>();
        for (Ingredients ingredients : ingredientsList) {
            Map<String, Object> map_object = new HashMap<>();
            map_object.put("materialId", ingredients.getId());//ID
            map_object.put("name", ingredients.getIngredientName());//食材名称
            map_object.put("amount", ingredients.getIngredientCount());//点评
            mapList_materials.add(map_object);
        }
        map.put("materials", mapList_materials);
        //根据菜谱Id,获取步骤列表
        List<CookingSteps> cookingStepsList = cookingStepsService.findByCookbookId(repiceId);
        List<Map<String, Object>> mapList_steps = new ArrayList<Map<String, Object>>();
        for (CookingSteps cookingSteps : cookingStepsList) {
            Map<String, Object> map_object = new HashMap<>();
            map_object.put("description", cookingSteps.getDescription());//描述
            map_object.put("image", Persistence.getValue(Constants.FILEIP) + cookingSteps.getImg());//原图
            mapList_steps.add(map_object);
        }
        map.put("steps", mapList_steps);
        resInfo.setResult(map);
        return resInfo;

    }


    /**
     * 点赞
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cookThumb", method = RequestMethod.GET)
    @ResponseBody
    public Object addCookThumb(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String userId = sessionVo.getUserId();
        Thumb thumb = thumbService.findByUserIdAndCookbookId(userId, requestInfo.getRepiceId());
        if (thumb == null) {
            thumb = new Thumb();
            thumb.setUserId(userId);
            thumb.setCookbookId(requestInfo.getRepiceId());//菜谱ID
            thumb.setStatus(BusinessConstants.THUMBSTATE.EFFECTIVE);//有效
            thumb.setCreateTime(new Date());
        } else {
            thumb.setStatus(BusinessConstants.THUMBSTATE.EFFECTIVE);//有效
            thumb.setUpdateTime(new Date());

        }
        thumbService.save(thumb);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;
    }


    /**
     * 取消点赞
     *
     * @param requestInfo
     * @param request
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/cancelThumb", method = RequestMethod.GET)
    @ResponseBody
    public Object cancelCookThumb(WeChatRequest requestInfo, HttpServletRequest request) throws Exception {
        WeChatResInfo resInfo = new WeChatResInfo();
        ServletContext application = request.getSession().getServletContext();
        if (application.getAttribute(requestInfo.getUserGuid()) == null) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("status", BusinessConstants.WECHAT_STATUS.E50010003);
            map.put("msg", "登陆权限已经过期");
            resInfo.setResult(map);
            return resInfo;
        }
        SessionVo sessionVo = (SessionVo) application.getAttribute(requestInfo.getUserGuid());
        String userId = sessionVo.getUserId();
        Thumb thumb = thumbService.findByUserIdAndCookbookId(userId, requestInfo.getRepiceId());
        if (thumb == null) {
            thumb = new Thumb();
            thumb.setUserId(userId);
            thumb.setCookbookId(requestInfo.getRepiceId());//菜谱ID
            thumb.setStatus(BusinessConstants.THUMBSTATE.INVALID);//取消
            thumb.setCreateTime(new Date());
        } else {
            thumb.setStatus(BusinessConstants.THUMBSTATE.INVALID);//取消
            thumb.setUpdateTime(new Date());

        }
        thumbService.save(thumb);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("status", BusinessConstants.WECHAT_STATUS.SUCCESS);
        map.put("msg", "成功");
        resInfo.setResult(map);
        return resInfo;
    }


}
